﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

// 状态栏
public class StatusBar: MonoBehaviour {
    private GameObject mLabelPrefab;    // 预制标签
    private List<GameObject> mLabels;   // 标签列表

    /**
     * 唤醒。
     */
    private void Awake() {
        // 初始化成员
        mLabelPrefab = transform.GetChild(0).gameObject;
        mLabels = new List<GameObject>();

        // 设置尺寸和位置
        RectTransform rectTransform = gameObject.GetComponent<RectTransform>();
        rectTransform.sizeDelta = new Vector2(Screen.width, rectTransform.sizeDelta.y);
        float y = -(Screen.height - rectTransform.sizeDelta.y) / 2;
        rectTransform.anchoredPosition = new Vector2(0, y);
    }

    /**
     * 添加标签。
     * @param title 标签标题
     */
    public void AddLabel(string title) {
        // 创建标签
        GameObject label = Instantiate(mLabelPrefab);
        label.SetActive(true);
        label.transform.SetParent(gameObject.transform);
        mLabels.Add(label);

        // 设置标签标题
        Text text = label.transform.GetComponentInChildren<Text>();
        text.text = title;

        // 设置标签尺寸和位置
        RectTransform rectTransform;
        float width = Screen.width / mLabels.Count;
        int i = 0;
        float x = 0;
        foreach (GameObject lab in mLabels) {
            rectTransform = lab.GetComponent<RectTransform>();
            rectTransform.sizeDelta = new Vector2(width, rectTransform.sizeDelta.y);
            x = -(Screen.width - width) / 2 + width * i;
            rectTransform.anchoredPosition = new Vector2(x, 0);
            i++;
        }
    }

    /**
     * 设置标签标题。
     * @param position  标签位置
     * @param title     标签标题
     */
    public void SetLabelTitle(int position, string title) {
        if (position >= mLabels.Count) {
            return;
        }

        mLabels[position].transform.GetComponentInChildren<Text>().text = title;
    }
}
